package org.example.nio.demo;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

public class NIOClient {
    public static void main(String[] args) {
        try {
            // 创建对象
            SocketChannel socketChannel = SocketChannel.open();
            // 设置通道为非阻塞
            socketChannel.configureBlocking(false);
            // 连接到指定地址
            socketChannel.connect(new InetSocketAddress("127.0.0.1",8080));
            // 等待线程完成连接
           while (!socketChannel.finishConnect()){
               Thread.yield();
           }
            // 输入内容
            Scanner scanner = new Scanner(System.in);
            String msg = scanner.nextLine();
            // 将一个byte数组包装成ByteBuffer对象
            ByteBuffer byteBuffer = ByteBuffer.wrap(msg.getBytes());
            // 由于是非阻塞的，如果在资源阻塞情况会直接返回，因此需要while
            while (byteBuffer.hasRemaining()){
                socketChannel.write(byteBuffer);
            }
            System.out.println("读取服务端返回的数据");
            ByteBuffer readBuff = ByteBuffer.allocate(1024);
            while (socketChannel.isConnected() && socketChannel.read(readBuff) != -1){
                if (readBuff.position() > 0)
                    break;
            }
            // 进入读取模式
            readBuff.flip();
            byte[] bytes = new byte[readBuff.limit()];
            readBuff.get(bytes);
            System.out.println(new String(bytes));
            scanner.close();
            socketChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
